<?php
/**
 * verifycode.class.php 验证码生成类
 *
 * @author          hyperblue
 * @version         0.1
 * @copyright       (C) 2011- *
 * @license	        http://www.bingceng.com
 * @lastmodify	    2011-08-10 14:50
 */
 
defined('BC_INC_PATH') or exit("Access Denied!");

class captcha {
    /*初始化*/
	public $border = 0; //是否要边框 1要:0不要
	public $how = 4; //验证码位数
	public $w; //图片宽度
	public $h = 20; //图片高度
	public $fontsize = 5; //字体大小
	public $alpha = "abcdefghijkmnpqrstuvwxyz"; //验证码内容1:字母
	public $number = "23456789"; //验证码内容2:数字
	public $verifyCode = ""; //验证码字符串初始化
	public $randcode;
	function __construct(){
		
		$this->w = $this->how*15; //图片宽度
	}
	
    /*绘制基本框架*/
    function Rectangle(){
    	srand((double)microtime()*1000000); //初始化随机数种子
        $bgcolor = ImageColorAllocate($this->im, 255, 255, 255); //设置背景颜色
        ImageFill($this->im, 0, 0, $bgcolor); //填充背景色
        if($this->border){
            $black = ImageColorAllocate($this->im, 0, 0, 0); //设置边框颜色
            ImageRectangle($this->im, 0, 0, $this->w-1, $this->h-1, $black);//绘制边框
        }
    }
	
    /*逐位产生随机字符*/
    function randcode(){
        for($i=0; $i<$this->how; $i++){
        	$j=0;
            $alpha_or_number = mt_rand(0, 1); //字母还是数字
            $str = $alpha_or_number ? $this->alpha : $this->number;
            $which = mt_rand(0, strlen($str)-1); //取哪个字符
            $code = substr($str, $which, 1); //取字符
            $j = !$i ? 4 : $j+15; //绘字符位置
            $color3 = ImageColorAllocate($this->im, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100)); //字符随即颜色
            ImageChar($this->im, $this->fontsize, $j, 3, $code, $color3); //绘字符
            $this->randcode .= $code; //逐位加入验证码字符串
        }
    }
	
    /*添加干扰*/
    function SetPixel(){
    	//绘背景干扰线
        for($i=0; $i<1; $i++){
            $color1 = ImageColorAllocate($this->im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); //干扰线颜色
            ImageArc($this->im, mt_rand(-5,$this->w), mt_rand(-5,$this->h), mt_rand(20,300), mt_rand(20,200), 55, 44, $color1); //干扰线
        }
        //绘背景干扰点
        for($i=0; $i<$this->how*5; $i++){
            $color2 = ImageColorAllocate($this->im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); //干扰点颜色
            ImageSetPixel($this->im, mt_rand(0,$this->w), mt_rand(0,$this->h), $color2); //干扰点
        }
    }
	
    //把验证码字符串写入session
    function setsession(){
        session_start();
        $_SESSION['VerifyCode'] = $this->randcode;
    }
	
    //创建生成的图片
	function showim(){
		$this->im = ImageCreate($this->w, $this->h); //创建验证图片
        $this->Rectangle();
        $this->randcode();
        $this->SetPixel();
        $this->setsession();
		return Imagegif($this->im);
	}
	
    /*绘图结束*/
    function __destruct(){
        ImageDestroy($this->im);
    }
    /*绘图结束*/

}
?>
